package com.marry.daodao.authserver.ui.security;

import com.google.common.base.Strings;
import com.marry.daodao.authserver.domain.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mal
 * @date 2022-11-15 14:22
 */
public class JWTTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Object principal = authentication.getPrincipal();

        Map<String, Object> additionalInfo = new HashMap<>();

        if (principal instanceof User) {
            User user = (User) principal;
            additionalInfo.put("userId", user.getUserId());
            additionalInfo.put("userPost", user.getUserPost());
            additionalInfo.put("name", user.getName());
            additionalInfo.put("officeId", user.getOfficeId());
            additionalInfo.put("distCode", user.getDistCode());
            additionalInfo.put("userRank", Strings.nullToEmpty(user.getUserRank()));

        }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;

    }
}
